package com.wq.httpclientcore.event;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wq.httpclientcore.entities.po.ApiConfig;
import com.wq.httpclientcore.entities.po.DbConnectionConfig;
import com.wq.httpclientcore.entities.po.DbQueryConfig;
import com.wq.httpclientcore.service.DbConnectionConfigService;
import com.wq.httpclientcore.service.DbQueryConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.List;

@Component
public class DbConnectionConfigDeletedEventListener {
    @Autowired
    private DbQueryConfigService dbQueryConfigService;

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) // 事务提交后触发
    public void handleDbConnectionConfigDeletedEvent(DbConnectionConfigDeletedEvent event) {
        List<Long> connectionIds = event.getDbConnectionIds();

        LambdaQueryWrapper<DbQueryConfig> queryWrapper = Wrappers.lambdaQuery(DbQueryConfig.class);
        queryWrapper.in(DbQueryConfig::getId, connectionIds);
        List<DbQueryConfig> queryConfigs = dbQueryConfigService.list(queryWrapper);

        for (DbQueryConfig queryConfig : queryConfigs) {
            queryConfig.setDbConnectionId(null);
        }

        if (!queryConfigs.isEmpty()) {
            dbQueryConfigService.updateBatchById(queryConfigs);
        }
    }
}

